package algorithm.leetcode.simple;

/*
 给定一个已按照升序排列 的有序数组，找到两个数使得它们相加之和等于目标数。
 函数应该返回这两个下标值 index1 和 index2，其中 index1 必须小于 index2
 */

import java.util.Arrays;

/**
 * @author jack.wu
 * @version 1.0
 * @date 2020/10/16
 */
public class Question167 {

    public static void main(String[] args) {
        int[] numbers = {2, 7, 11, 15};
        Question167 question = new Question167();
        int[] indexArray = question.twoSum(numbers, 9);
        System.out.println(Arrays.toString(indexArray));
    }

    public int[] twoSum(int[] numbers, int target) {
        int[] result = new int[2];
        if (numbers == null || numbers.length == 0) {
            return result;
        }

        int left = 0;
        int right = numbers.length - 1;
        while (left < right) {
            int sum = numbers[left] + numbers[right];
            if (sum > target) {
                right--;
            }else if (sum < target) {
                left++;
            }else {
                result[0] = left + 1;
                result[1] = right + 1;
                break;
            }
        }
        return result;
    }
}
